from flask import Blueprint, render_template, request, jsonify, redirect, url_for, flash
from flask_login import login_required, current_user
from app.models import User, Role, Permission, Log
from app.utils.permissions import admin_required, permission_required
from app.utils.logging_middleware import log_user_action
from app import db
from datetime import datetime

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.route('/')
@login_required
@admin_required
def dashboard():
    """管理员仪表板"""
    # 记录访问管理员仪表板日志
    log_user_action(
        action='访问管理员仪表板',
        details=f'管理员: {current_user.username}'
    )
    
    # 获取统计数据
    stats = {
        'total_users': User.query.count(),
        'active_users': User.query.filter_by(is_active=True).count(),
        'total_roles': Role.query.count(),
        'total_permissions': Permission.query.count()
    }
    
    # 获取最近活动（这里简化处理，实际项目中可以从日志表获取）
    recent_activities = []
    
    # 系统信息
    system_info = {
        'flask_version': '1.1.2',  # 实际项目中可以通过import flask; flask.__version__获取
        'python_version': '3.8.5',  # 实际项目中可以通过sys.version获取
        'database': 'SQLite',  # 实际项目中可以从配置获取
        'environment': 'Development',  # 实际项目中可以从配置获取
        'start_time': '2023-01-01 00:00:00',  # 实际项目中可以记录应用启动时间
        'current_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    return render_template('admin/dashboard.html', 
                          stats=stats, 
                          recent_activities=recent_activities,
                          system_info=system_info)

@admin_bp.route('/users')
@login_required
@admin_required
def users():
    """用户管理页面"""
    # 记录访问用户管理页面日志
    log_user_action(
        action='访问用户管理页面',
        details=f'管理员: {current_user.username}'
    )
    
    page = request.args.get('page', 1, type=int)
    per_page = 10
    search = request.args.get('search', '', type=str)
    
    # 构建查询
    query = User.query
    
    if search:
        query = query.filter(
            (User.username.contains(search)) | 
            (User.email.contains(search)) |
            (User.nickname.contains(search))
        )
    
    # 分页
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    users = pagination.items
    
    # 获取所有角色
    all_roles = Role.query.all()
    
    return render_template('admin/users.html', 
                          users=users, 
                          pagination=pagination,
                          all_roles=all_roles,
                          search=search)

@admin_bp.route('/roles')
@login_required
@admin_required
def roles():
    """角色管理页面"""
    # 记录访问角色管理页面日志
    log_user_action(
        action='访问角色管理页面',
        details=f'管理员: {current_user.username}'
    )
    
    # 获取所有角色
    roles = Role.query.all()
    
    # 获取所有权限
    all_permissions = Permission.query.all()
    
    return render_template('admin/roles.html', 
                          roles=roles, 
                          all_permissions=all_permissions)

@admin_bp.route('/permissions')
@login_required
@admin_required
def permissions():
    """权限管理页面"""
    # 记录访问权限管理页面日志
    log_user_action(
        action='访问权限管理页面',
        details=f'管理员: {current_user.username}'
    )
    
    # 获取所有权限
    permissions = Permission.query.all()
    
    return render_template('admin/permissions.html', permissions=permissions)

@admin_bp.route('/system-logs')
@login_required
@admin_required
def system_logs():
    """系统日志页面"""
    # 记录访问系统日志页面日志
    log_user_action(
        action='访问系统日志页面',
        details=f'管理员: {current_user.username}'
    )
    
    page = request.args.get('page', 1, type=int)
    per_page = 20
    level = request.args.get('level', '', type=str)
    search = request.args.get('search', '', type=str)
    
    # 构建查询
    query = Log.query
    
    if level:
        query = query.filter(Log.level == level)
    
    if search:
        query = query.filter(Log.message.contains(search))
    
    # 分页
    pagination = query.order_by(Log.created_at.desc()).paginate(page=page, per_page=per_page, error_out=False)
    logs = pagination.items
    
    return render_template('admin/system_logs.html', 
                          logs=logs, 
                          pagination=pagination,
                          level=level,
                          search=search)

@admin_bp.route('/clear-logs', methods=['POST'])
@login_required
@admin_required
def clear_logs():
    """清空系统日志"""
    try:
        # 记录清空日志前的操作
        log_user_action(
            action='清空系统日志',
            details=f'管理员: {current_user.username}'
        )
        
        Log.clear_all_logs()
        flash('系统日志已清空', 'success')
        
        # 记录清空日志的操作
        Log.info(
            message='系统日志已清空',
            ip_address=request.remote_addr,
            user_agent=request.headers.get('User-Agent'),
            url=request.url
        )
    except Exception as e:
        flash(f'清空日志失败: {str(e)}', 'danger')
    
    return redirect(url_for('admin.system_logs'))